import { useAliyunCaptcha } from '@/hooks/useAliyunCaptcha'
import type { VerifyResult } from '@/hooks/useAliyunCaptcha'
import { Button } from 'antd-mobile'
import { useSMS } from '../hooks/useSMS'
import { useCallback, useEffect } from 'react'
import type { InputRef } from 'antd-mobile/es/components/input'

export const SMSCaptcha = ({
    phoneRef,
    onResultUpdate,
    scene,
}: {
    phoneRef: React.RefObject<InputRef>
    onResultUpdate: (result?: VerifyResult) => void
    scene?: string
}) => {
    const { isSending, countdown, sendSMS } = useSMS()

    const onCaptchaBizCallback = useCallback(
        (res: boolean) => {
            if (res) {
                sendSMS(phoneRef.current?.nativeElement?.value ?? '', scene)
            }
        },
        [sendSMS, phoneRef, scene],
    )

    const { verifyResult } = useAliyunCaptcha({
        onBizResultCallback: onCaptchaBizCallback,
    })

    useEffect(() => {
        onResultUpdate(verifyResult)
    }, [verifyResult, onResultUpdate])

    return (
        <div id="captcha-button">
            <Button fill="none" disabled={isSending}>
                {isSending ? `${countdown}秒` : '获取验证码'}
            </Button>
            <div id="captcha-element" style={{ display: isSending ? 'none' : 'initial' }} />
        </div>
    )
}
